package com.lhkj.ct.meta.modules.report.word.personal;

import com.lhkj.ct.base.exception.SystemException;
import com.lhkj.ct.base.utils.file.FileUtils;
import com.lhkj.ct.base.utils.file.word.xwpf.CustomXWPFDocument;
import com.lhkj.ct.meta.modules.psychology.model.entity.TblScaleReportContent;
import com.lhkj.ct.meta.modules.psychology.model.vo.PersonalReportInfo;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.poi.xwpf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 描述
 * </p>
 *
 * @author job
 * @since 2023/10/22
 */
public class NormLayoutHandler extends BaseLayoutHandler<PersonalReportInfo>{

    private static final Logger logger = LoggerFactory.getLogger(NormLayoutHandler.class);

    private PersonalReportInfo data;

    private int tableIndex = 2;

    public NormLayoutHandler() {

    }

    @Override
    protected void init() {
        try ( InputStream is = FileUtils.readResourceFile("report\\个体报告常规模板.docx")){
            super.document = new CustomXWPFDocument(is);
        } catch (IOException e) {
            logger.error("模板加载失败,原因：==>{}", e.getMessage());
            throw new SystemException("模板加载失败");
        }
    }

    @Override
    public XWPFDocument build(PersonalReportInfo data) {
        this.data = data;
        // 报告标题
        super.builderTitle(data.getScaleName());
        // 基本信息
        super.builderBasicInfoTable(data.getBasicInfo());
        // 测验简介
        builderIntroduction();
        // 统计图表
        createChart();
        // 维度报告
        generateReportTable();
        // 审核人
        generateReviewer();
        return super.document;
    }

    /**
     * 测验简介
     */
    public void builderIntroduction() {
        document.getParagraphArray(3).createRun().setText(data.getBasicInfo().getIntroduction());
    }

    /**
     * 统计图表
     */
    private void createChart(){
        try {
            BufferedImage image = data.getChart().getBuildChart().apply(data);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", os);
            document.createPicture(
                    document.addPictureData(new ByteArrayInputStream(os.toByteArray()), XWPFDocument.PICTURE_TYPE_JPEG),
                    1,
                    image.getWidth(),
                    image.getHeight(),
                    document.getParagraphArray(5));
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<TblScaleReportContent> reportContents = data.getDimReport().stream()
                .filter(reportContent -> !BooleanUtils.toBoolean(reportContent.getFactor()))
                .collect(Collectors.toList());
        if (reportContents.isEmpty()) {
            word.getXwpfTableHelper().deleteTableByIndex(document, 1);
            return;
        }
        generateDimReportTable(document.getTableArray(1), reportContents);
    }

    /**
     * 生成维度报告
     */
    private void generateReportTable() {
        List<Map<String, Object>> repContent = new ArrayList<>();
        List<TblScaleReportContent> dimReport = data.getDimReport();
        for (TblScaleReportContent reportContent : dimReport) {
            if (BooleanUtils.toBoolean(reportContent.getFactor())) {
                continue;
            }
            Map<String, Object> map = new HashMap<>();
            map.put("dimName", reportContent.getDimName());
            map.put("explanation", reportContent.getExplanation());
            repContent.add(map);
        }
        if (repContent.isEmpty()) {
            word.getXwpfTableHelper().deleteTableByIndex(document, tableIndex);
            return;
        }
        for (int i = 0; i < repContent.size(); i++) {
            if (repContent.size() > 1 && i < repContent.size() - 1) {
                word.insetCopyTable(document, document.getTableArray(tableIndex), repContent.get(i + 1));
                document.createParagraph().createRun().addBreak();
            } else {
                word.replaceInTable(document.getTableArray(tableIndex), repContent.get(0));
            }
        }

        // 提示
        XWPFParagraph paragraph = document.createParagraph();
        paragraph.setAlignment(ParagraphAlignment.CENTER);// 居中对齐
        XWPFRun tips = paragraph.createRun();
        tips.setText("（本报告仅供参考，请以医生诊断为准。）");
        tips.setFontSize(11);
        tips.setFontFamily("宋体");
        tips.addBreak();
    }

    /**
     * 生成审核人信息
     */
    private void generateReviewer() {
        XWPFParagraph reviewerPara = document.createParagraph();
        reviewerPara.setVerticalAlignment(TextAlignment.CENTER);
        XWPFRun reviewerRun = reviewerPara.createRun();
        reviewerRun.setText("审核人：");
        reviewerRun.setBold(true);
        reviewerRun.setFontSize(11);
        reviewerRun.setFontFamily("宋体");
        super.sign(data.getBasicInfo(), reviewerRun);
    }
}
